package lastSymbol

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/Jeffail/gabs"
	kjson "github.com/heyuanlong/go-tools/json"
	"github.com/parnurzeal/gorequest"
)

type ZbPrice struct {
	httpDomain string
}

func NewZbPriceStruct() *ZbPrice {
	obj := &ZbPrice{}
	obj.init()
	return obj
}

func (ts *ZbPrice) init() {
	ts.httpDomain = "http://api.zb.live"
}

func (ts *ZbPrice) GetPriceUsdt(name string) (float64, error) {
	symbol := name + "_USDT"
	return ts.GetPrice(symbol)

}
func (ts *ZbPrice) GetPriceRmb(name string) (float64, error) {
	symbol := name + "_QC"
	return ts.GetPrice(symbol)
}

func (ts *ZbPrice) GetPrice(symbol string) (float64, error) {
	uri := ts.httpDomain + "/data/v1/ticker?market=" + symbol

	request := gorequest.New().Timeout(time.Duration(2) * time.Second)
	_, body, errs := request.Get(uri).End()
	if errs != nil {
		log.Println(errs)
		return 0, errs[0]
	}

	jsonParsed, err := gabs.ParseJSON([]byte(body))
	if err != nil {
		err = fmt.Errorf("get zb lasted price failed, err:%v\n", err.Error())
		return 0, err
	}

	s, err := kjson.GabsGetJsonString(jsonParsed, "ticker.last")
	if err != nil {
		log.Println(body, err)
		return 0, err
	}

	retv, errx := strconv.ParseFloat(s, 64)
	return retv, errx
}
